<template>
  <el-card>
    <h1>{{ id ? "编辑" : "创建" }}英雄</h1>
    <el-form :v-model="form" label-width="100px">
      <el-form-item label="名字">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <img v-if="form.avator" :src="form.avator" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save()">保存</el-button>
      </el-form-item>
    </el-form>
    
  </el-card>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      form: {
        name: '',
        avator: ''
      },
      parents: []
    };
  },
  created() {
    this.id && this.fetch();
    // this.getParent()
  },

  methods: {

     async fetch(){
          const rs = await this.$http.get(`rest/heroes/${this.id}`)
          this.form= rs.data
      },
    afterUpload(res) {
      console.log(res)
      this.form.avator = res.url
      
    },

    async getParent() {
      const rs = await this.$http.get("rest/heroes");
      this.parents = rs.data;
    },

    async save() {
      console.log(this.form);
      let rs;
      if (this.id) {
        rs = await this.$http.put(`rest/heroes/${this.id}`, this.form);
      } else {
        rs = await this.$http.post("rest/heroes", this.form);
      }
      if (rs.status !== 200) return;
      this.$message({
        message: "成功",
        type: "success"
      });
      this.$router.push({ path: "/heroes/list" });
    }
  }
};
</script>

<style lang="scss" scoped>
</style>>






